package com.javaEE.tes.security;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import javax.sql.DataSource;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Autowired
    DataSource dataSource;

    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.jdbcAuthentication().dataSource(dataSource)
                .usersByUsernameQuery("SELECT username, password, enabled " + "FROM user_accounts WHERE username= ?")
                .authoritiesByUsernameQuery("SELECT username, role " + "FROM user_accounts WHERE username = ?")
                .passwordEncoder(bCryptPasswordEncoder);
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
   http.authorizeRequests()
           .antMatchers("/student/new").hasRole("TEACHER")
           .antMatchers("/student/save").hasRole("TEACHER")
           .antMatchers("/association/new").hasRole("TEACHER")
           .antMatchers("/association/save").hasRole("TEACHER")
           .antMatchers("/class/new").hasRole("TEACHER")
           .antMatchers("/class/save").hasRole("TEACHER")
           .antMatchers("/courseSelection/new").hasRole("STUDENT")
           .antMatchers("/courseSelection/save").hasRole("STUDENT")
           .antMatchers("/curriculum/new").hasRole("TEACHER")
           .antMatchers("/curriculum/save").hasRole("TEACHER")
//           .antMatchers("/student/new").hasRole("ADMIN")
//           .antMatchers("/student/save").hasRole("ADMIN")
//           .antMatchers("/teacher/new").hasRole("ADMIN")
//           .antMatchers("/teacher/save").hasRole("ADMIN")
//           .antMatchers("/association/new").hasRole("ADMIN")
//           .antMatchers("/association/save").hasRole("ADMIN")
//           .antMatchers("/class/new").hasRole("ADMIN")
//           .antMatchers("/class/save").hasRole("ADMIN")
//           .antMatchers("/courseSelection/new").hasRole("ADMIN")
//           .antMatchers("/courseSelection/save").hasRole("ADMIN")
//           .antMatchers("/curriculum/new").hasRole("ADMIN")
//           .antMatchers("/curriculum/save").hasRole("ADMIN")
           .antMatchers("/","/**").permitAll()
           .and()
           .formLogin();

    }
}
